package cn.kooki.app.duobao.ui.Activity.Pay;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.iapppay.interfaces.callback.IPayResultCallback;
import com.iapppay.sdk.main.IAppPay;
import com.iapppay.sdk.main.IAppPayOrderUtils;
import com.ipaynow.plugin.api.IpaynowPlugin;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseNavActivity;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.User.bouns.BounsItem;
import cn.kooki.app.duobao.data.Bean.User.bouns.BounsResponse;
import cn.kooki.app.duobao.data.Bean.User.pay.PayResponse;
import cn.kooki.app.duobao.data.Bean.User.pay.PayResult;
import cn.kooki.app.duobao.data.Bean.User.pay.PayTypeRes;
import cn.kooki.app.duobao.data.Bean.cart.CartInfo;
import cn.kooki.app.duobao.data.Bean.cart.OrderInfo;
import cn.kooki.app.duobao.data.Bean.cart.OrderInfoItem;
import cn.kooki.app.duobao.data.bus.PayEvent;
import cn.kooki.app.duobao.data.bus.UserRefrshEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.ui.Adapter.OrderAdapter;
import cn.kooki.app.duobao.ui.widget.BankPicker;
import cn.kooki.app.duobao.ui.widget.CustomListView;
import cn.kooki.app.duobao.util.PayUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.SignUtils;
import cn.kooki.app.duobao.util.StringUtils;
import cn.kooki.app.duobao.util.TimeUtils;
import cn.kooki.app.duobao.util.manager.ShopCartManager;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2015/12/21.
 */
public class OrderAcitvity extends BaseNavActivity implements View.OnClickListener {
    @Bind(R.id.orderArr)
    ImageView orderArr;
    @Bind(R.id.amount)
    TextView amount;
    @Bind(R.id.orderListTitle)
    RelativeLayout orderListTitle;
    @Bind(R.id.cutHint)
    TextView cutHint;
    @Bind(R.id.renewHint)
    TextView renewHint;
    @Bind(R.id.hintLine)
    ImageView hintLine;
    @Bind(R.id.orderList)
    CustomListView orderList;
    @Bind(R.id.orderListContainer)
    LinearLayout orderListContainer;
    @Bind(R.id.useBonusTitle)
    TextView useBonusTitle;
    @Bind(R.id.bonusValue)
    TextView bonusValue;
    @Bind(R.id.useBonusCheckbox)
    CheckBox useBonusCheckbox;
    @Bind(R.id.useBonusValue)
    TextView useBonusValue;
    @Bind(R.id.useBonusOption)
    RelativeLayout useBonusOption;

    @Bind(R.id.useCoinTitle)
    TextView useCoinTitle;
    @Bind(R.id.coinValue)
    TextView coinValue;
    @Bind(R.id.useCoinCheckbox)
    CheckBox useCoinCheckbox;
    @Bind(R.id.useCoinValue)
    TextView useCoinValue;
    @Bind(R.id.useCoinOption)
    RelativeLayout useCoinOption;
    @Bind(R.id.useBankTitle)
    TextView useBankTitle;
    @Bind(R.id.useBankValue)
    TextView useBankValue;
    @Bind(R.id.useBankOption)
    RelativeLayout useBankOption;
    @Bind(R.id.banks)
    BankPicker banks;
    @Bind(R.id.submit)
    Button submit;
    @Bind(R.id.bonusList)
    RecyclerView bonusList;
    @Bind(R.id.bonusPicker)
    RelativeLayout bonusPicker;

    private boolean isopen = false;
    private UserInfo userinfo;
    private int totalcount;
    private PayResponse.PayInfo data;
    private int type;
    private PayResponse info;
    private BounsSelectAdpater bounsSelectAdpater;


    @Override
    public void setLayoutContainerView() {
        setContainerView(R.layout.activity_order);
        ButterKnife.bind(this);


    }

    private ArrayList<BounsItem> bounsItems = new ArrayList<>();

    @Override
    protected void afterView() {
        topTextCenter.setText(R.string.title_activity_order);
        topTextCenter.setVisibility(View.VISIBLE);
        setupViews();
        getbounslist();

    }

    private boolean isUseMoney;


    public void setupViews() {
        OrderAdapter adapter = new OrderAdapter(this);
        orderList.setAdapter(adapter);
        orderList.bindLinearLayout();
        orderListContainer.setVisibility(View.GONE);
        orderListTitle.setOnClickListener(this);
        userinfo = SharePreferencesUtils.getUserinfo(this);
        bonusPicker.setVisibility(View.GONE);

        totalcount = ShopCartManager.getInstance().getToalCount();
        int price = totalcount - StringUtils.nullSafeParseInt(userinfo.getMoney()) < 0 ? 0 : totalcount - StringUtils.nullSafeParseInt(userinfo.getMoney());
        amount.setText(totalcount + "抢宝币");
        useBankValue.setText("￥" + price);
        coinValue.setText("(账户余额：" + userinfo.getMoney() + "抢宝币)");
        useCoinCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isUseMoney = isChecked;
            }
        });
        if (StringUtils.nullSafeParseInt(userinfo.getMoney()) > 0) {
            useCoinCheckbox.setEnabled(true);
            useCoinCheckbox.setChecked(true);
        } else {
            useCoinCheckbox.setEnabled(false);
        }
        isUseMoney = useCoinCheckbox.isChecked();
        submit.setOnClickListener(this);
        useBonusCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    selected_index = 0;
                } else {
                    selected_index = -1;
                }
                refreshbouns();
            }
        });
        if (price == 0) {
            useBankOption.setVisibility(View.GONE);
            banks.setVisibility(View.GONE);
        } else {
            useBankOption.setVisibility(View.VISIBLE);
            banks.setVisibility(View.VISIBLE);
        }
        bounsSelectAdpater = new BounsSelectAdpater();
        bonusList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        bonusList.setAdapter(bounsSelectAdpater);
        bounsSelectAdpater.setLinstener(new BounsSelectLinstener() {
            @Override
            public void onSelect(int index) {
                selected_index = index;
                bonusList.smoothScrollToPosition(index);
                refreshbouns();
            }
        });
    }


    private void getbounslist() {
        MainFactory.getApiInstance().listbonus(userinfo.getUid(), 1, 0, totalcount + "", new Callback<BounsResponse>() {
            @Override
            public void success(BounsResponse bounsResponse, Response response) {
                if (bounsResponse.getData() != null) {
                    bounsItems.addAll(bounsResponse.getData());
                    refreshView();
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
        getPayType();
    }

    public int selected_index = -1;

    public interface BounsSelectLinstener {
        void onSelect(int index);
    }

    class BounsSelectAdpater extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private BounsSelectLinstener linstener;

        public void setLinstener(BounsSelectLinstener linstener) {
            this.linstener = linstener;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_bonus, parent, false);
            return new BonsViewholder(view);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            final BonsViewholder bonsViewholder = (BonsViewholder) holder;
            BounsItem bounsItem = bounsItems.get(position);
            bonsViewholder.checked.setVisibility(position == selected_index ? View.VISIBLE : View.GONE);
            String namestr = null;
            if (StringUtils.nullSafeParseInt(bounsItem.getFull_money()) > 0) {
                namestr = bounsItem.getTitle() + "满" + bounsItem.getFull_money() + "可用";
            }
            bonsViewholder.value.setText(bounsItem.getMoney());
            bonsViewholder.name.setText(namestr);
            bonsViewholder.expire.setText(TimeUtils.getTime(bounsItem.getEndtime()) + "到期");
            if (linstener != null) {
                bonsViewholder.bonus.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        linstener.onSelect(bonsViewholder.getLayoutPosition());
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return bounsItems.size();
        }

        class BonsViewholder extends RecyclerView.ViewHolder {

            @Bind(R.id.value)
            TextView value;
            @Bind(R.id.bonus)
            LinearLayout bonus;
            @Bind(R.id.name)
            TextView name;
            @Bind(R.id.expire)
            TextView expire;
            @Bind(R.id.checked)
            ImageView checked;
            @Bind(R.id.container)
            RelativeLayout container;

            public BonsViewholder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);

            }
        }
    }


    private void refreshView() {
        int price = totalcount - StringUtils.nullSafeParseInt(userinfo.getMoney())
                < 0 ? 0 : totalcount - StringUtils.nullSafeParseInt(userinfo.getMoney());
        if (bounsItems.size() > 0) {
            selected_index = 0;
        }
        refreshbouns();

    }


    public class BounsItemClickListener implements View.OnClickListener {

        private final int index;

        public BounsItemClickListener(int i) {
            this.index = i;
        }

        @Override
        public void onClick(View v) {

            for (int i = 0; i < bonusList.getChildCount(); i++) {
                View view = bonusList.getChildAt(i);
                View select = view.findViewById(R.id.checked);
                select.setVisibility(View.GONE);
                if (i == index) {
                    if (i == selected_index) {
                        selected_index = -1;
                        select.setVisibility(View.GONE);
                    } else {
                        selected_index = i;
                        select.setVisibility(View.VISIBLE);
                    }
                }
            }
            refreshbouns();
        }
    }

    /**
     * 刷新红包
     */
    private void refreshbouns() {
        bounsSelectAdpater.notifyDataSetChanged();
        if (bounsItems.size() > 0) {

            useBonusOption.setVisibility(View.VISIBLE);
            bonusPicker.setVisibility(View.VISIBLE);
            if (selected_index >= 0) {
                bonusPicker.setVisibility(View.VISIBLE);
                useBonusCheckbox.setChecked(true);
                useBonusValue.setText(bounsItems.get(selected_index).getMoney() + "抢宝币");

            } else if (selected_index == -1) {
                bonusPicker.setVisibility(View.GONE);
                useBonusValue.setText("未使用");
                useBonusCheckbox.setChecked(false);
            }
            int left = totalcount - StringUtils.nullSafeParseInt(userinfo.getMoney());
            if (selected_index >= 0) {
                left = left - StringUtils.nullSafeParseInt(bounsItems.get(selected_index).getMoney());
            }
            int price = left < 0 ? 0 : left;
            useBankValue.setText("￥" + price);
            if (price == 0) {
                useBankOption.setVisibility(View.GONE);
                banks.setVisibility(View.GONE);
            } else {
                useBankOption.setVisibility(View.VISIBLE);
                banks.setVisibility(View.VISIBLE);
            }
        } else {
            useBonusOption.setVisibility(View.GONE);
            bonusPicker.setVisibility(View.GONE);
        }

    }

    @Override
    public void onClick(View v) {
        if (v == orderListTitle) {
            isopen = !isopen;
            orderListContainer.setVisibility(isopen ? View.VISIBLE : View.GONE);
            if (isopen) {
                orderArr.setImageResource(R.drawable.ic_arr_up_gray);
            } else {
                orderArr.setImageResource(R.drawable.ic_arr_down_gray);
            }
        }
        if (v == submit) {
            if (checkform()) {
                getorderinfo();
            }
        }
    }

    private void getorderinfo() {
        showLoading("正在获取订单数据...");
        type = 0;
        if (banks.getSelectType() == BankPicker.WEIXIN_TYPE) {
            type = OrderInfo.WEIXIN_TYPE;
        } else if (banks.getSelectType() == BankPicker.AIBEI_TYPE) {
            type = OrderInfo.AIBEI_TYPE;
        }

        final OrderInfo orderInfo = new OrderInfo();
        orderInfo.list = new ArrayList<>();

        for (Map.Entry<String, CartInfo> entry : ShopCartManager.getInstance().getCarts().entrySet()) {
            CartInfo value = entry.getValue();
            OrderInfoItem item = new OrderInfoItem();
            item.num = value.count;
            item.shopid = value.id;
            orderInfo.list.add(item);
        }
        orderInfo.money_total = ShopCartManager.getInstance().getToalCount();
        if (bounsItems.size() > 0 && selected_index >= 0) {
            orderInfo.bonus_id = bounsItems.get(selected_index).getId();
        }
        orderInfo.pay_type = type;

        Gson gson = new Gson();
        String json = gson.toJson(orderInfo);

        MainFactory.getApiInstance().payorder(json, userinfo.getUid(), 4, new Callback<PayResponse>() {
            @Override
            public void success(PayResponse payResponse, Response response) {
                dismissLoading();
                if (payResponse.status == 0) {
                    info = payResponse;
                    if (payResponse.data != null) {
                        data = payResponse.data;
                        if (type == OrderInfo.WEIXIN_TYPE) {
                            weixinpay();
                        } else {
                            aibeiPay();
                        }
                    } else {
                        PayEvent payEvent = new PayEvent();
                        payEvent.isSuccess = true;
                        onEventMainThread(payEvent);
                    }
                } else {
                    showToastMessage(payResponse.msg);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                dismissLoading();
                showToastMessage("网络错误");
            }
        });
    }

    private void aibeiPay() {
        IAppPay.startPay(this, "transid=" + data.transid + "&appid=" + Constants.IPAY_APP_ID, iPayResultCallback);
    }


    private String TAG = "IPAY";
    /**
     * 支付结果回调
     */
    IPayResultCallback iPayResultCallback = new IPayResultCallback() {

        @Override
        public void onPayResult(int resultCode, String signvalue, String resultInfo) {
            // TODO Auto-generated method
            PayEvent event = new PayEvent();
            switch (resultCode) {
                case IAppPay.PAY_SUCCESS:
                    //调用 IAppPayOrderUtils 的验签方法进行支付结果验证
                    boolean payState = IAppPayOrderUtils.checkPayResult(signvalue, PayConfig.publicKey);
                    if (payState) {
                        Toast.makeText(OrderAcitvity.this, "支付成功", Toast.LENGTH_LONG).show();
                        event.isSuccess = true;
                    }
                    break;
                case IAppPay.PAY_ING:
                    Toast.makeText(OrderAcitvity.this, "成功下单", Toast.LENGTH_LONG).show();
                    break;
                default:
                    Toast.makeText(OrderAcitvity.this, resultInfo, Toast.LENGTH_LONG).show();
                    break;
            }
            EventBus.getDefault().post(event);
            Log.d(TAG, "requestCode:" + resultCode + ",signvalue:" + signvalue + ",resultInfo:" + resultInfo);
        }
    };


    private void getPayType() {
        MainFactory.getApiInstance().getPayType(new Callback<PayTypeRes>() {
            @Override
            public void success(PayTypeRes payTypeRes, Response response) {
                if (payTypeRes.data != null) {
                    fitterType(payTypeRes.data);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                showToastMessage("获取支付方式失败");
                finish();
            }
        });
    }

    private void fitterType(ArrayList<String> data) {
        if (banks != null) {
            int hideType = -1;
            if (!data.contains("聚合")) {
                hideType = BankPicker.WEIXIN_TYPE;
            } else if (!data.contains("爱贝")) {
                hideType = BankPicker.AIBEI_TYPE;
            }
            if (hideType != -1) {
                banks.hideProgress(type);
            } else {
                banks.hideProgress();
            }
        }
    }

    public void onEventMainThread(PayEvent event) {

        if (event.isSuccess) {
            EventBus.getDefault().post(new UserRefrshEvent());
            ShopCartManager.getInstance().clearCarts();
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("type", PayCallBackActivity.ORDER_TYPE);
            hashMap.put("code", info.dingdan);
            hashMap.put("pay_code", info.pay_dingdan);
            intent2(PayCallBackActivity.class, hashMap);
        }
        finish();
    }

    private void weixinpay() {
        String sing = data.sign.replaceAll("\\\\", "");
        IpaynowPlugin.pay(this, sing);
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        PayEvent event = new PayEvent();

        String respCode = data.getExtras().getString("respCode");
        String errorCode = data.getExtras().getString("errorCode");
        String respMsg = data.getExtras().getString("respMsg");

        StringBuilder temp = new StringBuilder();
        if (TextUtils.equals(respCode, "00")) {
            event.isSuccess = true;
            temp.append("交易状态:成功");
        }

        if (TextUtils.equals(respCode, "02")) {
            temp.append("交易状态:取消");
        }

        if (TextUtils.equals(respCode, "01")) {
            temp.append("交易状态:失败").append("\n").
                    append("错误码:" + errorCode).
                    append("原因:" + respMsg);
        }

        if (TextUtils.equals(respCode, "03")) {
            temp.append("交易状态:未知").append("\n").
                    append("错误码:" + errorCode).
                    append("原因:" + respMsg);
        }
        EventBus.getDefault().post(event);
        Toast.makeText(this, temp.toString(), Toast.LENGTH_LONG).show();

    }


    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    public String sign(String content) {
        return SignUtils.sign(content, Constants.RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    public String getSignType() {
        return "sign_type=\"RSA\"";
    }

    private boolean checkform() {
        int limt = StringUtils.nullSafeParseInt(userinfo.getMoney()) - totalcount;

        if (bounsItems.size() > 0 && selected_index >= 0) {
            BounsItem item = bounsItems.get(selected_index);

            limt = limt + StringUtils.nullSafeParseInt(item.getMoney());
        }
        if (limt < 0 && banks.getSelectType() == -1) {
            showToastMessage("请选择支付途径");
            return false;
        }
        return true;
    }

}
